package com.johnny.xia.util.xml;

import com.alibaba.fastjson.JSON;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * @ClassName PriceXmlUtil
 * @Author johnny xia
 * @mailto johnny.xia@qq.com
 * @Date 2021/8/26 10:13 下午
 * @Description TODO
 **/
public class PriceXmlUtil {

  public static void main(String[] args) throws DocumentException {
/*
    SAXReader reader = new SAXReader();
    Document document = reader.read(new File("/Users/johnny/Documents/project/johnny/java/johnnyxia.util/src/main/resources/test.xml"));
    Element rootElement = document.getRootElement();
    List<Element> prices = new ArrayList<>();
    getElement(rootElement,"PRICES_RSP_ARTICLE_AND_BATCH",prices);
    for(Element element : prices){
      Element priceNode = element.element("item");
      System.out.println(getElementValue(priceNode,"MATNR"));
    }

    */

    //FLOW_STOCK
    SAXReader reader = new SAXReader();
    Document document = reader.read(new File("/Users/johnny/Documents/project/johnny/java/johnnyxia.util/src/main/resources/test2.xml"));
    Element rootElement = document.getRootElement();
    Element SEM_IMPORT = rootElement.element("SQL1").element("SEM_IMPORT").element("access");
    System.out.println(rootElement.getName());
    System.out.println(getElementValue(SEM_IMPORT,"flow_id"));


//
//    List<Element> accessList = new ArrayList<>();
//    getElement(rootElement,"access",accessList);
//    for(Element element : accessList){
//      System.out.println("REFERENCE:"+getElementValue(element,"REFERENCE"));
//    }

//



  }

  private static void getElement(Element element,String name,List<Element> result){
    if(element.getName().equals(name)){
      result.add(element);
    }else{
      List<Element> elements = element.elements();
      if(elements.size() > 0){
        for(Element e : elements){
          getElement(e,name,result);
        }
      }
    }
  }

  private static String getElementValue(Element element,String key){
    if(element.element(key) == null){
      return null;
    }
    return element.element(key).getStringValue();

  }
}
